package com.android.delivery.base;

import android.app.ActivityManager;
import android.app.Application;
import android.content.Context;
import android.os.Process;

import com.ada.common.util.CollectionUtil;
import com.blankj.utilcode.util.LogUtils;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

/**
 * description:基础的Application实现了activity的记录和一些必要的初始化工作
 */
public abstract class BaseApplication extends Application {
	private static final String TAG = "BaseFrame.Application";
	//当前进程的名称
//	private String mCurProcessName;


	private List<WeakReference<BaseActivity>> mActivites;
	private BaseActivityLifecycleCallback mActivityLifecycleCallback ;

	@Override
	public void onCreate() {
		super.onCreate();

		init();

		if (isMainProcess(getApplicationContext())){
			mActivites = new ArrayList<>(8);
			registerLifecycleCallbacks(getActivityLifecycleCallback());
			initInMainProcess();
		}
	}

	public boolean isMainProcess(Context context) {
		String processName = AppUtils.getProcessName(context);
		return processName != null && !processName.contains(":");
	}

	/***业务Application的初始化*/
	protected abstract void init();

	protected void initInMainProcess(){

	}

	/**获取当前进程名*/
//	public String getCurProcessName(){
//		return mCurProcessName;
//	}

//	@Override
//	protected void attachBaseContext(Context base) {
//		super.attachBaseContext(base);
//		mCurProcessName = AppUtil.getCurProcessName(this);
//	}

	/**获取Activity生命周期回调*/
	protected BaseActivityLifecycleCallback getActivityLifecycleCallback(){
		return null;
	}

	private void registerLifecycleCallbacks(BaseActivityLifecycleCallback lifecycleCallback){
		if (lifecycleCallback == null){
			mActivityLifecycleCallback = new BaseActivityLifecycleCallback();
		}else {
			mActivityLifecycleCallback = lifecycleCallback;
		}
		registerActivityLifecycleCallbacks(mActivityLifecycleCallback);
	}

	@Override
	public void onTerminate() {
		super.onTerminate();
		LogUtils.d(TAG, "onTerminate");
	}

	@Override
	public void onTrimMemory(int level) {
		super.onTrimMemory(level);
		LogUtils.d(TAG, "onTrimMemory level=", level);
	}

	@Override
	public void onLowMemory() {
		super.onLowMemory();
		LogUtils.d(TAG, "onLowMemory");
	}

	/**添加Activity，用于退出的时候管理*/
	protected final void addActivity(BaseActivity activity){
		if (mActivites != null && activity != null){
			WeakReference<BaseActivity> weakReference = new WeakReference<>(activity);
			if (mActivites.contains(weakReference)) {
				return;
			}
			mActivites.add(new WeakReference<>(activity));
		}
	}

	/**移除Activity，用于退出的时候管理*/
	protected void removeActivity(BaseActivity activity){
		if (mActivites != null && activity != null){
			if (mActivites.isEmpty()){
				return;
			}

			for (WeakReference<BaseActivity> wrf : mActivites){
				if (wrf == null || wrf.get() == null){
					continue;
				}
				BaseActivity item = wrf.get();
				if (item.getClass().isAssignableFrom(activity.getClass())){
					mActivites.remove(wrf);
					break;
				}
			}
		}
	}

	/**退出应用*/
	public void exitApp(){
		LogUtils.d(TAG, "exitApp");
		closeAllActivities();
		if (mActivityLifecycleCallback != null){
			unregisterActivityLifecycleCallbacks(mActivityLifecycleCallback);
		}
		killSelfAllProcess();

	}

	public final void closeAllActivities(){
		if (mActivites != null && !mActivites.isEmpty()){
			LogUtils.d(TAG, "activity size=", mActivites.size());
			//尝试关闭所有页面
			int length = mActivites.size();
			for (int i = 0; i < length; i++){
				WeakReference<BaseActivity> weakReference = mActivites.get(i);
				if (weakReference == null) {
					continue;
				}
				BaseActivity activity = weakReference.get();
				if (activity == null) {
					continue;
				}
				if (activity.isFinishing()) {
					continue;
				}
				activity.finish();
			}
			mActivites.clear();
		}
	}

	protected final void killSelfAllProcess(){
		String pkgName = getPackageName();
		ActivityManager am = (ActivityManager)getSystemService(Context.ACTIVITY_SERVICE);
		List<ActivityManager.RunningAppProcessInfo> processInfos = am.getRunningAppProcesses();
		if (!CollectionUtil.isEmptyOrNull(processInfos)){
			for (ActivityManager.RunningAppProcessInfo processInfo : processInfos){
				if (!pkgName.equals(processInfo.processName) && processInfo.processName.startsWith(pkgName)){
					//杀死所有子进程
					LogUtils.d(TAG, "processName=", processInfo.processName, " ,pid=", processInfo.pid);
					Process.killProcess(processInfo.pid);
				}
			}
		}
		Process.killProcess(Process.myPid());
		System.exit(0);
	}

	public boolean isActivityInStack(Class clazz){
		if (clazz == null || mActivites == null || mActivites.isEmpty()){
			return false;
		}

		for (WeakReference<BaseActivity> wrf : mActivites){
			if (wrf == null || wrf.get() == null){
				continue;
			}
			BaseActivity activity = wrf.get();
			if (activity.getClass().isAssignableFrom(clazz)){
				return true;
			}
		}
		return false;
	}



}
